package search.Adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.xfengshopping.R;
import search.Product;
import com.squareup.picasso.Picasso;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {

    private List<Product> productList;

    public ProductAdapter(List<Product> productList) {
        this.productList = productList;
    }

    @NonNull
    @Override
    public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_product_search, parent, false);
        return new ProductViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ProductViewHolder holder, int position) {
        Product product = productList.get(position);

        holder.goodsName.setText(product.getGoodsName());
        holder.goodsIntro.setText(product.getGoodsIntro());
        holder.sellingPrice.setText(String.format("¥%.2f", product.getSellingPrice()));

        // 使用Picasso加载图片，添加占位图和错误图
        Picasso.get()
                .load(product.getGoodsCoverImg())
                .placeholder(R.drawable.ic_placeholder) // 添加占位图
                .error(R.drawable.ic_error) // 添加错误图
                .into(holder.goodsCoverImg);

        /*// 添加点击事件
        holder.itemView.setOnClickListener(v -> {
            // 跳转到商品详情页
            // Intent intent = new Intent(v.getContext(), ProductDetailActivity.class);
            // intent.putExtra("product_id", product.getGoodsId());
            // v.getContext().startActivity(intent);
        });*/
    }




    @Override
    public int getItemCount() {
        return productList.size();
    }

    public static class ProductViewHolder extends RecyclerView.ViewHolder {
        ImageView goodsCoverImg;
        TextView goodsName;
        TextView goodsIntro;
        TextView sellingPrice;

        public ProductViewHolder(@NonNull View itemView) {
            super(itemView);
            goodsCoverImg = itemView.findViewById(R.id.goodsCoverImg);
            goodsName = itemView.findViewById(R.id.goodsName);
            goodsIntro = itemView.findViewById(R.id.goodsIntro);
            sellingPrice = itemView.findViewById(R.id.sellingPrice);
        }
    }
    /*public void updateData(List<Product> newProducts) {
        Set<Long> existingIds = new HashSet<>();
        for (Product p : productList) {
            existingIds.add(p.getGoodsId());
        }

        for (Product p : newProducts) {
            if (!existingIds.contains(p.getGoodsId())) {
                productList.add(p);
            }
        }
        notifyDataSetChanged();
    }*/
}
